package com.zaimokuza.cn.config.security;

import com.zaimokuza.cn.entity.enums.CustomizeExceptionEnum;
import com.zaimokuza.cn.util.grace.GraceResponse;
import com.zaimokuza.cn.util.HttpUtils;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理
 *
 * @author zaimokuza
 */
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (exception instanceof InternalAuthenticationServiceException) {
            // 没有找到用户名对应的用户
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_NOT_REGISTER));
        } else if (exception instanceof LockedException) {
            // 用户被锁定
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_IS_LOCKED));
        } else if (exception instanceof DisabledException) {
            // 用户被禁用
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_IS_DISABLED));
        } else if (exception instanceof AccountExpiredException) {
            // 账户过期
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_ACCOUNT_EXPIRE));
        } else if (exception instanceof CredentialsExpiredException) {
            // 密码过期
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_PASSWORD_EXPIRE));
        } else if (exception instanceof BadCredentialsException) {
            // 用户名或密码错误
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_BAD_CREDENTIALS));
        } else {
            // 其他异常提示登录失败
            HttpUtils.response(response, GraceResponse.error(CustomizeExceptionEnum.USER_LOGIN_FAILURE));
        }
    }

}
